3. Clustered Index Seeks
The first two index creations in Listing 1
create clustered indexes on the SalesOrderHeader and Product tables.
Then comes a query. Then the listing creates a clustered index on the
SalesOrderDetail table. Finally, the query is executed again, showing
the improvement from using a clustered index over the table scan.
Example 1. SQL Script to Create Clustered Indexes and Retrieve Data from the Newly Created Tables
CREATE CLUSTERED INDEX ix_SalesOrderId ON apWriter.SalesOrderHeader(SalesOrderId)
CREATE CLUSTERED INDEX ix_ProductId ON apWriter.Product(ProductId)
SELECT * FROM apWriter.SalesOrderDetail WHERE SalesOrderId = 74853
CREATE CLUSTERED INDEX ix_SalesOrderIdDetailId ON apWriter.SalesOrderDetail(SalesOrderId,SalesOrderDetailId)
SELECT * FROM apWriter.SalesOrderDetail WHERE SalesOrderId = 74853
|
Figure 1 shows the execution plans from executing Listing 1.
Notice the missing index message. You are notified of missing indexes
by default in SQL Server 2008. The information in that message is the
same that you could get manually by querying the missing index views
described earlier.
Also notice the cost
difference between the table scan and the clustered index seek. If you
run your multiple table query for a sales order, you will see that
clustered index seeks are used instead of table scans. For example,
execute the following query. You should see an execution plan like that
shown in Figure 2.
SELECT soh.SalesOrderId, soh.OrderDate, soh.ShipDate,p.Name, sod.OrderQty,
sod.UnitPrice, sod.LineTotal
FROM apWriter.SalesOrderHeader soh
JOIN apWriter.SalesOrderDetail sod ON soh.SalesOrderId = sod.salesOrderId
JOIN apWriter.Product p ON sod.ProductId = p.ProductId
WHERE soh.SalesOrderId = 74853